//
//  NetHelper.swift
//  eBooks
//
//  Created by JunMing on 2019/11/6.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import Alamofire

class NetModel: NSObject {
    var urlString:String = ""
    var methodType:HTTPMethod = .get
    var parameters:[String:String]?
    var isAnimation:Bool = true
}

class NetHelper: NSObject {
    var alamoFire:SessionManager?
}

extension NetHelper {
    static let share:NetHelper = {
        let share = NetHelper()
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 10
        share.alamoFire = Alamofire.SessionManager(configuration: config)
        return share
    }()
    
    func requestData(urlString:String,methodType:HTTPMethod,parameters:[String:String]?,finished:@escaping (_ result:AnyObject?, _ error:NSError?) -> Void) {
        self.alamoFire?.request(urlString, method: methodType, parameters: parameters, encoding: URLEncoding.default).responseJSON(completionHandler: { (response) in
            if response.result.isSuccess {
                finished(response.result.value as AnyObject, nil)
            }else {
                finished(nil,response.result.error as NSError?)
            }
        })
    }
    
    func downloadWith(urlStr url: String, dest destUrl:URL=FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0], success:@escaping (_ result:String,_ status:Bool)-> Void,progress:@escaping (_ progress:Double?) -> Void) {
        //指定下载路径（文件名不变）
        let destination: DownloadRequest.DownloadFileDestination = { _, response in
            let fileURL = destUrl.appendingPathComponent(response.suggestedFilename!)
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        
        Alamofire.download(url, to: destination).downloadProgress { (pro) in
                progress(pro.fractionCompleted)
            }.responseData { (response) in
                if response.response?.statusCode == 404 {
                    print("download Error!")
                    success("download Error!" ,false)
                }else {
                    if let data = response.result.value {
                        if data.count > 300 {
                            success("download success!",true)
                        }
                    }
                }
        }
    }
    
    func uploadWith(urlStr url: String, success:@escaping (_ result:AnyObject,_ error:Error?)-> Void) {
        let fileURL = URL(fileURLWithPath: url)
        let header:HTTPHeaders = [
            "Content-Type":"multipart/form-data; boundary=----WebKitFormBoundary47AyMUCSzOdBVBi5;charset=utf-8"
        ]
        Alamofire.upload(fileURL, to: "http://192.168.0.107:10086/upload.html", headers: header).validate().responseData { (DDataRequest) in
            if DDataRequest.result.isSuccess {
                print(String.init(data: DDataRequest.data!, encoding: String.Encoding.utf8)!)
            }
            if DDataRequest.result.isFailure {
                print("上传失败！！！")
            }
        }
    }
}
